/*
 * @(#)SimpleMultipartRequestEntity.java, 2009-2-22
 *
 * Copyright 2009 SuperV System Integration CO., LTD. All rights reserved.
 */
package org.lex.net.http;

import java.io.UnsupportedEncodingException;
import java.util.Random;

import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 * 
 * 
 * @author Liu Er Xiao
 * @version 1.0, 2009-2-22
 */
public class SimpleMultipartRequestEntity extends MultipartRequestEntity {

	public static String generateBoundary() {
		Random rand = new Random();
		int len = rand.nextInt(11) + 30;
		StringBuilder buf = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			buf.append(alphabet[rand.nextInt(alphabet.length)]);
		}
		return buf.toString();
	}

	private static final String BOUNDARY_PREFIX = "--";
	private static final char[] alphabet = { '-', '_', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
			'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
			'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

	private static final HttpMethodParams PARAMS = new HttpMethodParams();
	private final byte[] boundary;

	public SimpleMultipartRequestEntity(Part... parts) {
		this(parts, null);
	}

	public SimpleMultipartRequestEntity(Part[] parts, String boundary) {
		super(parts, PARAMS);
		byte[] tmp = null;
		if (null != boundary && 0 != boundary.trim().length()) {
			if (false == boundary.startsWith(BOUNDARY_PREFIX)) {
				boundary = BOUNDARY_PREFIX + boundary;
			}
			try {
				tmp = boundary.getBytes("ISO-8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				tmp = null;
			}
		}
		this.boundary = tmp;
	}

	@Override
	protected byte[] getMultipartBoundary() {
		if (null == this.boundary) {
			return super.getMultipartBoundary();
		} else {
			return this.boundary;
		}
	}

}